package com.artup.service.impl;

import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;

import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.artup.common.Constants;
import com.artup.common.ResponseResult;
import com.artup.dao.MemberDao;
import com.artup.pojo.Member;
import com.artup.service.AuthorityWebService;
import com.artup.util.md5.MD5Util2;
import com.artup.util.md5.MD5Utils;

@Service( value = "authorityWebService" )
@Transactional( readOnly = false )
public class AuthorityWebServiceImpl implements AuthorityWebService {
	protected static final Logger LOGGER = LoggerFactory.getLogger(AuthorityWebServiceImpl.class);
	
	@Autowired
	private MemberDao memberDao;

	@Override
	public ResponseResult signin(String username, String password, String securityCode, String clientIP, HttpSession httpSession ) {
		LOGGER.info("username = " + username + ", clientIP = " + clientIP);
		LOGGER.info("httpSession.getId() = " + (httpSession.getId()));
		System.out.println("sessionID = " + httpSession.getId());
		
		ResponseResult response = new ResponseResult();
		
		if(StringUtils.isBlank(securityCode)) {
			response.setStatus(Constants.ACTION_STATUS_FAILURE);
			response.setMessage("请输入验证码！");
			
			return response;
		} 
		System.out.println("securityCode = " + httpSession.getAttribute("securityCode"));
		if( null == httpSession.getAttribute("securityCode") ) {
			response.setStatus(Constants.ACTION_STATUS_FAILURE);
			response.setMessage("验证码已失效！请重新获取。");
			
			return response;
		} 
		if(!httpSession.getAttribute("securityCode").equals(securityCode)) {
			response.setStatus(Constants.ACTION_STATUS_FAILURE);
			response.setMessage("验证码不正确！");
			
			return response;
		}
		
		Member member = null;
		try {
			member = this.memberDao.selectMemberByUsername(username);
		} catch (Exception e) {
			LOGGER.error("根据【用户名】查询【会员】 - 失败！", e);
			
			response.setStatus(Constants.ACTION_STATUS_FAILURE);
			response.setMessage("根据【用户名】查询【会员】 - 失败！");
		}
		
		if(null == member) {
			response.setStatus(Constants.ACTION_STATUS_FAILURE);
			response.setMessage("无此会员！");
			
			return response;
		}
		
		try {
			if(!MD5Util2.validPassword(password, member.getPassword())) {
				response.setStatus(Constants.ACTION_STATUS_FAILURE);
				response.setMessage("用户名或密码错误！");
				
				return response;
			}
		} catch (ArrayIndexOutOfBoundsException | NoSuchAlgorithmException | UnsupportedEncodingException e) {
			LOGGER.error("密码校验错误", e);
		}
		
		// TODO 用户足记记录到 MongoDB 中
		
		httpSession.setAttribute("member", member);	// 放入到 HTTP 会话中
		
		response.setStatus(Constants.ACTION_STATUS_SUCCESS);
		response.setData(member);
		response.setMessage("登入成功。");
		
		return response;
	}

	@Override
	public ResponseResult register(String username, String password, String nickname, String securityCode, String clientIP, HttpSession httpSession ) {
		LOGGER.info("username = " + username + ", clientIP = " + clientIP);
		
		ResponseResult response = new ResponseResult();
		
		if(StringUtils.isBlank(securityCode)) {
			response.setStatus(Constants.ACTION_STATUS_FAILURE);
			response.setMessage("请输入验证码！");
			
			return response;
		} else if(!httpSession.getAttribute(httpSession.getId()).equals(securityCode)) {
			response.setStatus(Constants.ACTION_STATUS_FAILURE);
			response.setMessage("验证码不正确！");
			
			return response;
		}
		
		Member member = null;
		try {
			member = this.memberDao.selectMemberByUsername(username);
		} catch (Exception e) {
			LOGGER.error("根据【用户名】查询【用户】 - 失败！", e);
			
			response.setStatus(Constants.ACTION_STATUS_FAILURE);
			response.setMessage("根据【用户名】查询【用户】 - 失败！");
		}
		
		if(null != member) {
			response.setStatus(Constants.ACTION_STATUS_FAILURE);
			response.setMessage("用户名已存在！");
			
			return response;
		}
		
		member = new Member();
		member.setUsername(username);
		try {
			member.setPassword(MD5Utils.getEncryptedPasswordd(password));
		} catch (NoSuchAlgorithmException e) {
			LOGGER.error("没有这样的运算 - 失败！", e);
			
			response.setStatus(Constants.ACTION_STATUS_FAILURE);
			response.setMessage("密码加密 - 失败！");
		} catch (UnsupportedEncodingException e) {
			LOGGER.error("不支持的字符编码 - 失败！", e);
			
			response.setStatus(Constants.ACTION_STATUS_FAILURE);
			response.setMessage("密码加密 - 失败！");
		}
		member.setNickname(nickname);
		try {
			this.memberDao.insertMember(member);
		} catch (Exception e) {
			LOGGER.error("保存【会员】 - 失败！", e);
			
			response.setStatus(Constants.ACTION_STATUS_FAILURE);
			response.setMessage("保存【会员】 - 失败！");
		}
		
		response.setStatus(Constants.ACTION_STATUS_SUCCESS);
		response.setMessage("注册成功。");
		
		return response;
	}

	@Override
	public ResponseResult signout( HttpSession httpSession, String username ) {
		LOGGER.info("username = " + username);
		
		ResponseResult response = new ResponseResult();
		
		httpSession.removeAttribute("member");	// 将“会员”从会话中清除
		
		response.setStatus(Constants.ACTION_STATUS_SUCCESS);
		response.setMessage("退出成功。");
		
		return response;
	}
}
